﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using DevExpress.XtraTreeList.Nodes;
using DevExpress.XtraEditors;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using DevExpress.Utils;
using DevExpress.Utils.Menu;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraTreeList.Columns;
using DevExpress.XtraGrid.Localization;
using DevExpress.XtraGrid.Menu;
using DevExpress.XtraTreeList;
using System.Drawing;
using DevExpress.XtraTreeList.Menu;

namespace ElingAppSystemCtrls
{
    public partial class EASTreeList : DevExpress.XtraTreeList.TreeList
    {
        /// <summary>
        /// 配置文件路径
        /// </summary>
        private string FilePath = "";
        /// <summary>
        /// 构造函数
        /// </summary>
        public EASTreeList()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 有参构造函数
        /// </summary>
        /// <param name="container"></param>
        public EASTreeList(IContainer container)
        {
            container.Add(this);
            InitializeComponent();
        }

        /// <summary>
        /// 结束初始化
        /// </summary>
        protected override void OnEndInit()
        {
            base.OnEndInit();
            if (!this.DesignMode)
            {
                string lastVerson = this.LastGridLayoutDate;
                string filepathBase = AppDomain.CurrentDomain.BaseDirectory + "ClientConfig" + "\\";

                DateTime? codeDate = null;
                DateTime? configDate = null;
                if (!string.IsNullOrEmpty(lastVerson))
                {
                    codeDate = DateTime.Parse(lastVerson);
                    this.OptionsLayout.LayoutVersion = codeDate.Value.ToString("yyyy-MM-dd");
                }

                Control ownForm = this.FindForm();
                string parentName = "";
                if (ownForm != null)
                {
                    parentName = ownForm.Name;
                }
                else
                {
                    parentName = this.Parent.Name;
                }
                FilePath = filepathBase + parentName + "_" + this.Name + ".xml";
                if (File.Exists(FilePath))
                {
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.Load(FilePath);
                    XmlNode xmlNode = xmlDoc.SelectSingleNode("//property[@name='#LayoutVersion']");
                    DateTime tmpDate;
                    if (DateTime.TryParse(xmlNode.InnerXml, out tmpDate))
                    {
                        configDate = tmpDate;
                    }

                    if (codeDate != null && configDate != null)
                    {
                        if (codeDate > configDate)
                        {
                            File.Delete(FilePath);
                        }
                        else
                        {
                            this.RestoreLayoutFromXml(FilePath);
                        }

                    }
                    else
                    {
                        File.Delete(FilePath);
                    }
                }

                if (File.Exists(FilePath))
                {

                    this.RestoreLayoutFromXml(FilePath, OptionsLayoutBase.FullLayout);
                }
                
                this.PopupMenuShowing += new DevExpress.XtraTreeList.PopupMenuShowingEventHandler(EASTreeList_PopupMenuShowing);
                this.NodeCellStyle += new GetCustomNodeCellStyleEventHandler(EASTreeList_NodeCellStyle);
               
                foreach (TreeListColumn treeCol in this.Columns)
                {
                    if (treeCol.AbsoluteIndex == 0)
                    {
                        treeCol.OptionsColumn.AllowMove = false;
                    }
                    if (treeCol.AppearanceHeader.TextOptions.HAlignment == HorzAlignment.Default)
                    {
                        treeCol.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
                    }
                }
                if (!string.IsNullOrEmpty(this.LastGridLayoutDate))
                {
                    this.ColumnChanged += new DevExpress.XtraTreeList.ColumnChangedEventHandler(EASTreeList_ColumnChanged);
                    this.ColumnWidthChanged += new DevExpress.XtraTreeList.ColumnWidthChangedEventHandler(EASTreeList_ColumnWidthChanged);
                }
            }
        }

        private void EASTreeList_NodeCellStyle(object sender, GetCustomNodeCellStyleEventArgs e)
        {
            if (this.Name == "tlstTaxPreForm")
            {
                if (!e.Node.HasChildren)
                {
                    //纳税申报
                    object obj = e.Node.GetValue("SettleInfoStatus");
                    if (obj != null)
                    {
                        switch (obj.ToString())
                        {
                            case "N"://新单
                            case "P"://缴费
                            case "R"://冲红
                                {
                                    //正常
                                    e.Appearance.ForeColor = Color.FromArgb(0, 0, 0);
                                    break;
                                }
                            case "C":
                                {
                                    //作废
                                    e.Appearance.ForeColor = Color.FromArgb(255, 0, 0);
                                    break;
                                }
                        }
                    }
                }
                else
                {
                    //判断下级的结算项目是否都已经作废了
                    bool isAllInvalid = true;
                    foreach (TreeListNode node in e.Node.Nodes)
                    {
                        object obj = node.GetValue("SettleInfoStatus");
                        if (obj != null)
                        {
                            if (obj.ToString() != "C")
                            {
                                isAllInvalid = false;
                                break;
                            }
                        }
                    }
                    if (isAllInvalid)
                    {
                        //作废
                        e.Appearance.ForeColor = Color.FromArgb(255, 0, 0);
                    }
                }

            }
        }
       
        /// <summary>
        /// 列宽改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void EASTreeList_ColumnWidthChanged(object sender, DevExpress.XtraTreeList.ColumnChangedEventArgs e)
        {
            EASTreeList tlst = (EASTreeList)sender;
            string filepathBase = AppDomain.CurrentDomain.BaseDirectory + "ClientConfig" + "\\";
            if (!Directory.Exists(filepathBase))
            {
                Directory.CreateDirectory(filepathBase);
            }
            tlst.SaveLayoutToXml(FilePath, OptionsLayoutBase.FullLayout);
        }
        /// <summary>
        /// 列改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void EASTreeList_ColumnChanged(object sender, DevExpress.XtraTreeList.ColumnChangedEventArgs e)
        {
            if (e.Column != null)
            {
                EASTreeList tlst = (EASTreeList)sender;
                string filepathBase = AppDomain.CurrentDomain.BaseDirectory + "ClientConfig" + "\\";
                if (!Directory.Exists(filepathBase))
                {
                    Directory.CreateDirectory(filepathBase);

                }
                tlst.SaveLayoutToXml(FilePath, OptionsLayoutBase.FullLayout);
            }
        }
        #region 表格右键相关
        /// <summary>
        /// 表格右键弹出菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void EASTreeList_PopupMenuShowing(object sender, DevExpress.XtraTreeList.PopupMenuShowingEventArgs e)
        {
            EASTreeList easTreeList = (EASTreeList)sender;
            if (e.Menu.MenuType == TreeListMenuType.Column)
            {

                //// Customize
                //DXMenuItem miCustomize = GetItemByStringId(e.Menu, GridStringId.MenuColumnColumnCustomization);
                //if (miCustomize != null)
                //{
                //    miCustomize.Visible = false;
                //}

                List<DXMenuItem> visibleMenuList = new List<DXMenuItem>()
                {
                    GetItemByStringId(e.Menu, GridStringId.MenuColumnGroup),
                    GetItemByStringId(e.Menu, GridStringId.MenuGroupPanelShow),
                    GetItemByStringId(e.Menu, GridStringId.MenuGroupPanelHide),
                    GetItemByStringId(e.Menu, GridStringId.MenuColumnRemoveColumn),
                    GetItemByStringId(e.Menu, GridStringId.MenuColumnColumnCustomization)
                };
                foreach (DXMenuItem dxItem in visibleMenuList)
                {
                    if (dxItem != null)
                    {
                        dxItem.Visible = false;
                    }
                }

                TreeListColumnMenu menu = e.Menu as TreeListColumnMenu;
                if (menu.Column != null)
                {
                    //添加菜单 
                    menu.Items.Add(CreateTreeListCheckItem("冻结列", menu.Column, DevExpress.XtraTreeList.Columns.FixedStyle.Left,
                      null));
                }

            }
        }
        /// <summary>
        /// 获取右键菜单资源
        /// </summary>
        /// <param name="menu"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        private DXMenuItem GetItemByStringId(DXPopupMenu menu, GridStringId id)
        {
            foreach (DXMenuItem item in menu.Items)

                if (item.Caption == GridLocalizer.Active.GetLocalizedString(id))

                    return item;

            return null;
        }

        /// <summary>
        /// 创建右键菜单
        /// </summary>
        /// <param name="caption"></param>
        /// <param name="column"></param>
        /// <param name="style"></param>
        /// <param name="image"></param>
        /// <returns></returns>
        private DXMenuCheckItem CreateTreeListCheckItem(string caption, TreeListColumn column, DevExpress.XtraTreeList.Columns.FixedStyle style, Image image)
        {
            DXMenuCheckItem item = new DXMenuCheckItem(caption, column.Fixed == style, image, new EventHandler(OnEASTreeListFixedClick));
            item.Tag = new EASTreeListMenuInfo(column, style, item.Checked);
            return item;
        }
        /// <summary>
        /// 点击冻结列
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnEASTreeListFixedClick(object sender, EventArgs e)
        {
            DXMenuItem item = sender as DXMenuItem;
            EASTreeList easTreeList = this;
            easTreeList.Update();
            EASTreeListMenuInfo info = item.Tag as EASTreeListMenuInfo;
            if (info == null)
            {
                return;
            }
            if (!info.Checked)
            {
                for (int i = 0; i < easTreeList.VisibleColumns.Count; i++)
                {
                    if (easTreeList.VisibleColumns[i].Caption.ToLower().Trim() == info.Column.Caption.ToLower().Trim())
                    {
                        ApplayTreeListFix(easTreeList.VisibleColumns[i].Caption, DevExpress.XtraTreeList.Columns.FixedStyle.Left, easTreeList);
                        if (i == easTreeList.VisibleColumns.Count - 1)
                            easTreeList.VisibleColumns[i].BestFit();
                        break;
                    }
                    ApplayTreeListFix(easTreeList.VisibleColumns[i].Caption, DevExpress.XtraTreeList.Columns.FixedStyle.Left, easTreeList);
                }
            }
            else if (info.Checked)
            {
                for (int i = easTreeList.VisibleColumns.Count - 1; i >= 0; i--)
                {
                    easTreeList.VisibleColumns[i].Fixed = DevExpress.XtraTreeList.Columns.FixedStyle.None;
                }
            }
            DevExpress.XtraTreeList.ColumnChangedEventArgs ee = new ColumnChangedEventArgs(easTreeList.FocusedColumn);
            EASTreeList_ColumnChanged(easTreeList, ee);
        }
        /// <summary>
        /// 设置表格列冻结
        /// </summary>
        /// <param name="sCol"></param>
        /// <param name="fr"></param>
        private void ApplayTreeListFix(string sCol, DevExpress.XtraTreeList.Columns.FixedStyle fr, TreeList easTreeList)
        {
            foreach (TreeListColumn grCol in easTreeList.VisibleColumns)
            {
                if (grCol.Caption.ToString() == sCol)
                {
                    grCol.Fixed = fr;
                    return;
                }
            }
        }
        /// <summary>
        /// TreeList右键菜单信息类
        /// </summary>
        private class EASTreeListMenuInfo
        {
            public EASTreeListMenuInfo(TreeListColumn column, DevExpress.XtraTreeList.Columns.FixedStyle style, bool check)
            {
                this.Column = column;
                this.Style = style;
                this.Checked = check;
            }
            public DevExpress.XtraTreeList.Columns.FixedStyle Style;
            public TreeListColumn Column;
            public bool Checked;
        }
        #endregion
        #region 属性
        /// <summary>
        /// 最近表格布局日期
        /// </summary>
        [Category(CategoryName.Properties), Description("最近表格布局日期(如:2012-08-12),为空则表示表格布局不保存"), DefaultValue("")]
        public string LastGridLayoutDate
        {
            set;
            get;
        }
        #endregion
    }

    public class CustomTLNode : TreeListNode
    {
        public CustomTLNode(int id, TreeListNodes owner)
            : base(id, owner)
        {
        }
        private string NodeParameters()
        {
            string s = "Node " + this.Id.ToString();
            if (this.HasChildren)
            {
                s += "; ChildNodes Count = " + this.Nodes.Count;
                if (this.Expanded)
                    s += "; Expanded";
            }
            if (this.Tag != null && !this.Tag.Equals(""))
                s += "; Tag: " + this.Tag.ToString();
            return s;
        }
        public override object this[object columnID]
        {
            get { return NodeParameters(); }
            set
            {
                if (columnID.Equals(this.TreeList.Columns[0]))
                {
                    this.Tag = value;
                    this.TreeList.LayoutChanged();
                }
            }
        }
    }
}

